import { jwtDecode } from 'jwt-decode'

// Token存储键名
const TOKEN_KEY = 'teach_token'

export default {
    // 存储Token
    setToken(token) {
        localStorage.setItem(TOKEN_KEY, token)
    },

    // 获取Token
    getToken() {
        return localStorage.getItem(TOKEN_KEY)
    },

    // 移除Token
    removeToken() {
        localStorage.removeItem(TOKEN_KEY)
    },

    // 判断是否登录
    isLogin() {
        return !!this.getToken()
    },

    // 从Token中获取用户信息
    getUserInfo() {
        const token = this.getToken()
        if (!token) return null

        try {
            return jwtDecode(token)
        } catch (error) {
            return null
        }
    },

    // 获取用户类型
    getUserType() {
        const userInfo = this.getUserInfo()
        return userInfo ? userInfo.userType : null
    },

    // 获取用户ID
    getUserId() {
        const userInfo = this.getUserInfo()
        return userInfo ? userInfo.userId : null
    },

    getUserName() {
        const userInfo = this.getUserInfo()
        return userInfo ? userInfo.userName : null
    },
}